package com.tgb.lk.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.tgb.lk.config.Config;
import com.tgb.lk.config.ConfigXmlUtil;
import com.tgb.lk.table.Log;
import com.tgb.lk.table.TableConfig;

public class VelocityUtill {

	public VelocityContext getVelocityContext() {
		VelocityContext ctx = new VelocityContext();
		ConfigXmlUtil util = new ConfigXmlUtil();
		Config config = util.getConfig();
		if (config != null) {
			ctx.put("templates-dir", config.getTemplatesDir());
			ctx.put("fixed-files-dir", config.getFixedFilesDir());
			ctx.put("beans-dir", config.getBeansDir());
			ctx.put("beans-package", config.getBeansPackage());
			ctx.put("libs-dir", config.getLibsDir());
			ctx.put("dest-code-dir", config.getDestCodeDir());
			ctx.put("base-package", "com.tgb.lk");// 放置一个默认的变量,模板中默认可引用,如果程序中设置了会覆盖本变量.

			// 设置Hibernate配置文件的连接方式.
			TableConfig tableConfig = TableConfig.getInstance();
			ctx.put("url", tableConfig.getDbConnectString());
			ctx.put("username", tableConfig.getDbUsername());
			ctx.put("password", tableConfig.getDbPasswd());
			int dbType = tableConfig.getDataBaseType();
			if (dbType == AppConstants.DB_SQLSERVER) {
				ctx.put("driver_class", "net.sourceforge.jtds.jdbc.Driver");
				ctx.put("dialect", "org.hibernate.dialect.SQLServerDialect");
			} else if (dbType == AppConstants.DB_ORACLE) {
				ctx.put("driver_class", "oracle.jdbc.driver.OracleDriver");
				ctx.put("dialect", "org.hibernate.dialect.OracleDialect");
			} else {
				ctx.put("driver_class", "com.mysql.jdbc.Driver");
				ctx.put("dialect", "org.hibernate.dialect.MySQLDialect");
			}
		}
		validateFile(config.getLibsDir() + File.separator
				+ "auto-annotation.jar", "res/.libs/auto-annotation.jar");
		return ctx;
	}

	private void validateFile(String filePath, String jarInPath) {
		filePath = FileUtil.filterDir(filePath);
		File file = new File(filePath);
		// System.out.println("filePath======"+filePath);
		if (!file.exists()) {
			Log.log("copy files:" + filePath, 1);
//			String oldPath = "/resources/" + jarInPath;
			String oldPath = "/"+jarInPath;
			FileUtil.copyFile(this.getClass().getResourceAsStream(oldPath),
					FileUtil.makeFilePath(filePath));
		}
	}

	private void validateFolder(String filePath, String jarInPath) {
		filePath = FileUtil.filterDir(filePath);
		File file = new File(filePath);
		if (!file.exists()) {
			InputStream in = this.getClass().getResourceAsStream(
					"/filelist.txt");
			InputStreamReader reader;
			BufferedReader bufferedReader;
			String tempString = null;
			// 一次读入一行，直到读入null为文件结束
			try {
				reader = new InputStreamReader(in);
				bufferedReader = new BufferedReader(reader);
				while ((tempString = bufferedReader.readLine()) != null) {
					if (tempString.startsWith(jarInPath)) {
						FileUtil.copyFile(this.getClass().getResourceAsStream(
								"/" + tempString), FileUtil
								.makeFilePath(filePath
										+ tempString.replace(jarInPath, "")));
					}
				}
				bufferedReader.close();
				reader.close();
			} catch (IOException e1) {
				Log.log(e1);
				e1.printStackTrace();
			}

		}
	}

	/**
	 * 生成文件
	 * 
	 * @param cxt
	 *            上下文
	 * @param templatePath
	 *            模板路径
	 * @param destPath
	 *            生成的文件路径
	 */
	public static void write(VelocityContext cxt, String templatePath,
			String destPath) throws ResourceNotFoundException,
			ParseErrorException, Exception {
		templatePath = FileUtil.filterDir(templatePath);
		destPath = FileUtil.filterDir(destPath);
		Velocity.setProperty(Velocity.RESOURCE_LOADER, "MyResourceLoader");
		Velocity.setProperty("MyResourceLoader.resource.loader.class",
				"com.tgb.lk.util.MyResourceLoader");
		String charsetName = FileUtil.getChartsetName(templatePath);
		charsetName = charsetName == null ? System.getProperty("file.encoding")
				: charsetName;
		// Log.log("文件字符编码" + charsetName,5);
		Template template = Velocity.getTemplate(templatePath, charsetName);
		String dirPath = destPath.substring(0, destPath
				.lastIndexOf(File.separator));
		File dirFile = new File(dirPath);

		if (!dirFile.exists()) {
			if (!dirFile.mkdirs()) {
				throw new RuntimeException(dirFile + "文件夹创建失败");
			}
		}

		OutputStream os = new FileOutputStream(destPath);
		OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
		template.merge(cxt, writer);
		writer.flush();
		writer.close();
	}

	public static void main(String[] args) {
		// VelocityContext cxt= new VelocityContext();
		//		
		// try {
		// VelocityUtill.write(cxt, "..\\autossh_temp\\resources\\Bean.hbm.xml",
		// "d:/bean.xml");
		// } catch (ResourceNotFoundException e) {
		// e.printStackTrace();
		// } catch (ParseErrorException e) {
		// e.printStackTrace();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// VelocityUtill.getVelocityContext();
		// VelocityUtill util = new VelocityUtill();
		// util.getVelocityContext();

		// validateFolder("D:\\autossh_temp\\templates\\fixed","resource/fixed");
		// validateFolder("D:\\autossh_temp\\templates\\others",
		// "resources/others");

		getJarFile();
	}

	/**
	 * 控制台打印
	 */
	public static void print(String destPath) throws IOException {
		destPath = FileUtil.filterDir(destPath);
		File file = new File(destPath);
		System.out.println(file.getAbsolutePath());
		InputStream in = null;
		InputStreamReader reader = null;
		in = new FileInputStream(file);
		reader = new InputStreamReader(in, "UTF-8");
		BufferedReader bufferReader = new BufferedReader(reader);

		StringBuffer stringBuffer = new StringBuffer("");
		String str = null;
		while ((str = bufferReader.readLine()) != null) {
			stringBuffer.append(str + "\r\n");
		}
		System.out.println(stringBuffer);

		bufferReader.close();
		reader.close();
		in.close();

	}

	public static void getJarFile() {
		JarFile jarFile;
		try {
			jarFile = new JarFile("resources.jar");
			Enumeration<JarEntry> enum1 = jarFile.entries();
			while (enum1.hasMoreElements()) {
				JarEntry entry = (JarEntry) enum1.nextElement();
				if (entry.isDirectory()) {
                    continue;
                }
				// 下面这个字符串保存着不是目录的资源（如图片）或类（如.class文件）
				String jar = entry.getName();
				System.out.println(jar);
			}
		} catch (IOException e) {
			Log.log(e);
			e.printStackTrace();
		}

	}
}
